package com.hzhc.common;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.hzhc.annotation.SysTemLog;
import com.hzhc.dto.UserDto;
import com.hzhc.entity.SysExceptionLog;
import com.hzhc.entity.SysLog;
import com.hzhc.mapper.SysExceptionLogMapper;
import com.hzhc.mapper.SysLogMapper;
import com.hzhc.utils.HttpContextUtils;
import com.hzhc.utils.IpUtils;
import com.hzhc.utils.TokenUtil;
import lombok.RequiredArgsConstructor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @description AOP 日志
 * @author duanhm
 * @version 创建时间：2019年6月19日 下午4:24:58
 *
 */

@Aspect
@Component
@RequiredArgsConstructor
@SuppressWarnings("all")
public class SystemLogAspect {
	protected Logger logger = LogManager.getLogger(getClass());

//	private final VersionInfoMapper versionInfoMapper;

	private final SysLogMapper sysLogMapper;

	private final SysExceptionLogMapper exceptionLogMapper;

	/**
	 * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
	 */
	// @Pointcut("within(@org.springframework.stereotype.Controller *)")
//	@Pointcut("@within(org.springframework.stereotype.Controller) || @within(org.springframework.web.bind.annotation.RestController)")
	@Pointcut("@annotation(com.hzhc.annotation.SysTemLog)")
	public void cutController() {
	}


	/**
	 * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
	 */
	@Pointcut("execution(* com.hzhc.controller..*.*(..))")
	public void operExceptionLogPoinCut() {
	}

	// @SuppressWarnings("unchecked")
	@Around("cutController()")
	public Object recordSysLog(ProceedingJoinPoint point) throws Throwable {
		// 从获取RequestAttributes中获取HttpServletRequest的信息
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		try {
			// 获取请求的类名
			String strClassName = point.getTarget().getClass().getName();
			// 从切面织入点处通过反射机制获取织入点处的方法
			MethodSignature signature = (MethodSignature) point.getSignature();
			// 获取切入点所在的方法
			Method method = signature.getMethod();
			// 获取请求的方法名
			String strMethodName = method.getName();
			SysLog sysLog = new SysLog();
			// 获取操作
			SysTemLog sysTemLog = method.getAnnotation(SysTemLog.class);
			String operType = "";
			String operDesc = "";
			String modular = "";
			String operModul = "";
			String loginName = "";
			String realName = "";
			if (sysTemLog != null) {
				operType = sysTemLog.operType();
				operDesc = sysTemLog.operDesc();
				modular = sysTemLog.modular();
				operModul = sysTemLog.operModul();
			}
			sysLog.setMenuName(operModul); // 操作模块
			sysLog.setOperType(operType); // 操作类型
			sysLog.setMenuDesc(operDesc); // 操作描述
			sysLog.setAccesspath(modular); // 项目模块 PC和WXAPP

			sysLog.setClassName(strClassName);
			sysLog.setMethodName(strMethodName);
			// 请求的参数
			Map<String, String> rtnMap = converMap(request.getParameterMap());
			// 将参数所在的数组转换成json
			String bfParams = rtnMap.toString();
			String body = HttpContextUtils.getBodyString(request);
			String strMessage="";
			if(StrUtil.isNotBlank(bfParams)){
				strMessage = String.format("[类名]:%s,[方法]:%s,[参数]:%s", strClassName, strMethodName, bfParams);
			}else if(StrUtil.isNotBlank(body)){
				strMessage = String.format("[类名]:%s,[方法]:%s,[参数]:%s", strClassName, strMethodName, body);
			}


			logger.info(strMessage);
			if ("login".equals(strMethodName) || "loginMember".equals(strMethodName)) {
				//调用执行目标方法(result为目标方法执行结果)
				Object result=point.proceed();
				sysLog.setOptContent("");
			} else {
				sysLog.setOptContent(bfParams);
			}
			sysLog.setCreateTime(LocalDateTime.now());
			if (request != null) {
				sysLog.setClientIp(IpUtils.getIpAddr(request));
			}
			String token = request.getHeader("token");
			if(StrUtil.isNotBlank(token)){
				UserDto user =  TokenUtil.getUser(request);
				sysLog.setLoginName(user.getLoginname());
				sysLog.setRealname(user.getRealname());
			}else if(strMethodName.contains("login")){
				// 解析请求体的内容
				JSONObject json = JSONObject.parseObject(body.toString());
				// 处理JSON对象
				String name = json.getString("loginname");
				sysLog.setLoginName(name);
			}
//			VersionInfo versionInfos = versionInfoMapper.selectOne(
//					new LambdaQueryWrapper<VersionInfo>()
//							.orderByDesc(VersionInfo::getCreateTime)
//							.last("limit 1"));
//			if(versionInfos != null){
//				sysLog.setOperVer(versionInfos.getVersionNo()); // 操作版本
//			}
			sysLogMapper.insert(sysLog);
		}catch (Exception e){
			e.printStackTrace();
		}
		return point.proceed();
	}


	/**
	 * 异常返回通知，用于拦截异常日志信息 连接点抛出异常后执行
	 *
	 * @param joinPoint 切入点
	 * @param e         异常信息
	 */
	@AfterThrowing(pointcut = "operExceptionLogPoinCut()", throwing = "e")
	public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
		// 获取RequestAttributes
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		// 从获取RequestAttributes中获取HttpServletRequest的信息
		HttpServletRequest request = (HttpServletRequest) requestAttributes
				.resolveReference(RequestAttributes.REFERENCE_REQUEST);
		SysExceptionLog excepLog = new SysExceptionLog();
		try {
			// 从切面织入点处通过反射机制获取织入点处的方法
			MethodSignature signature = (MethodSignature) joinPoint.getSignature();
			// 获取切入点所在的方法
			Method method = signature.getMethod();
			//excepLog.setExcId(UuidUtil.get32UUID());
			// 获取请求的类名
			String className = joinPoint.getTarget().getClass().getName();
			// 获取请求的方法名
			String methodName = method.getName();
			methodName = className + "." + methodName;
			// 请求的参数
			Map<String, String> rtnMap = converMap(request.getParameterMap());
			// 将参数所在的数组转换成json
			String params = JSON.toJSONString(rtnMap);
			excepLog.setExcRequParam(params); // 请求参数
			excepLog.setOperMethod(methodName); // 请求方法名
			excepLog.setExcName(e.getClass().getName()); // 异常名称
			excepLog.setExcMessage(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace())); // 异常信息
			String token = request.getHeader("token");
			if(StrUtil.isNotBlank(token)){
				UserDto user =  TokenUtil.getUser(request);
				excepLog.setUserId(user.getId());
				excepLog.setOperUserName(user.getRealname());
			}else if(methodName.contains("login")){
				String body = HttpContextUtils.getBodyString(request);
				// 解析请求体的内容
				JSONObject json = JSONObject.parseObject(body.toString());
				// 处理JSON对象
				String name = json.getString("loginname");
				excepLog.setOperUserName(name);
			}

			excepLog.setOperUri(request.getRequestURI()); // 操作URI
			excepLog.setOperIp(IpUtils.getIpAddr(request)); // 操作员IP
//			List<VersionInfo> versionInfos = versionInfoMapper.selectList(Wrappers.<VersionInfo>lambdaQuery()
//					.orderByDesc(VersionInfo::getCreateTime));
//			if(versionInfos.size()>0){
//				excepLog.setOperVer(versionInfos.get(0).getVersionNo()); // 操作版本
//			}
			excepLog.setCreateTime(LocalDateTime.now()); // 发生异常时间
			exceptionLogMapper.insert(excepLog);
		} catch (Exception e2) {
			e2.printStackTrace();
		}

	}

	/**
	 * 转换request 请求参数
	 *
	 * @param paramMap request获取的参数数组
	 */
	public Map<String, String> converMap(Map<String, String[]> paramMap) {
		Map<String, String> rtnMap = new HashMap<String, String>();
		for (String key : paramMap.keySet()) {
			rtnMap.put(key, paramMap.get(key)[0]);
		}
		return rtnMap;
	}

	/**
	 * 转换异常信息为字符串
	 *
	 * @param exceptionName    异常名称
	 * @param exceptionMessage 异常信息
	 * @param elements         堆栈信息
	 */
	public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
		StringBuffer strbuff = new StringBuffer();
		for (StackTraceElement stet : elements) {
			strbuff.append(stet + "\n");
		}
		String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
		return message;
	}
}
